Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

128
Vistas
¿Cómo encontrar el elemento de matriz del documento por su campo "_id" en MongoDB (Mongoose)?

Tengo el siguiente esquema (NestJS + Mongoose):

 @Schema({ timestamps: true }) export class Listing { @Prop({ type: [{ bidderId: { type: Types.ObjectId, required: true, select: false, ref: User.name, index: true }, amount: { type: Number, required: true }, date: { type: Date, required: true } }], select: false }) bids!: Bid[] }

así que básicamente cada documento de listing tiene una serie de bids .
ahora me doy cuenta de que automáticamente mongoDB (o mangosta) crea un campo _id para cada artículo de oferta que pongo en la matriz de bids .

Mi pregunta es: si tengo el _id de una oferta, ¿cómo puedo consultar su elemento de la matriz de ofertas de la lista? algo como:

 // Adding a new bid to the listing, and retrieving the updated listing const listingWithAddedBid = await this.listingModel.findByIdAndUpdate(listingId, { $push: { bids: { $each: [{ amount: bidInfo.amount, bidderId: new Types.ObjectId(user.id), date: new Date() }], $sort: { amount: -1 } } } }, { new: true }) // Getting the new bid's _id from the array (it will be at index 0 because we sort buy amount) const newBidId = listingWithAddedBid.bids[0]._id // here how can I query the entire bid item from the array with 'newBidId'? this won't work this.listingModel.findById(newBidId) // returns null
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

https://docs.mongodb.com/manual/tutorial/query-array-of-documents/ https://docs.mongodb.com/manual/indexes/#default-_id-index

 this.listingModel.findOne({ "bids._id": newBidId, {}, {}, (error, doc) => { if (error) { .... } if (doc) { .... } else { ...//'Not Found'; } });
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda